<template>
    <div>
        <!--      搜索框-->
        <div style="min-height: 100px;margin:0 10px; padding:10px 10px;background: white" class="search-div">
            <a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form"
                :model="searchFormState" @finish="searchDataSource">
<!--                搜索框-->
                <a-row :gutter="24">
<!--                    <div>{{userSearchColumns}}</div>-->
                    <template v-for="(searchColumnItem,index) in userSearchColumns" :key="index">
                        <a-col v-show="searchExpand || index <= 5" :span="4">
                            <a-form-item v-if="searchColumnItem.inputType=='input'"
                                    :name="searchColumnItem.name"
                                    :label="searchColumnItem.label"
                                    :rules="[{ required: false }]"
                            >
                                <a-input v-model:value="searchFormState[searchColumnItem.name]" :placeholder="searchColumnItem.placeHolder || '请输出值'"></a-input>
                            </a-form-item>
                            <a-form-item v-if="searchColumnItem.inputType=='dropdown'"
                                         :name="searchColumnItem.name"
                                         :label="searchColumnItem.label"
                                         :rules="[{ required: false }]"
                            >
                                <a-select
                                        placeholder="请选择身份"
                                        v-model:value="searchFormState[searchColumnItem.name]"
                                        style="width: 200px"
                                        :allowClear="true"
                                >
                                    <a-select-option v-for="{selectKey,selectName} in searchColumnItem.selectList"
                                                     :value="selectKey"
                                                     :key="selectKey">
                                        {{ selectName }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                    </template>
                </a-row>
<!--               -->
                <a-row>
                    <a-col :span="24" style="text-align: right">
                        <a-button type="primary" html-type="submit">搜索</a-button>
                        <a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
                        <a v-if="userSearchColumns.length>5" style="font-size: 12px" @click="searchExpand = !searchExpand">
                            <template v-if="searchExpand">
                                <UpOutlined />
                                收起
                            </template>
                            <template v-else>
                                <DownOutlined />
                                展开
                            </template>
                        </a>
                    </a-col>
                </a-row>

            </a-form>
        </div>
        <!--      表单-->
        <div class="form-div" style="margin:10px;padding:5px;background: white;">
<!--              操作按钮-->
            <div class="button-div">
                <a-button type="primary" style="margin:0 10px" @click="showAddModal">
                    新增
                </a-button>
                <a-button type="primary">
                    导出
                </a-button>
            </div>
<!--          表单区域-->
                <a-table row-key="userId" :row-selection="rowSelection" v-model:dataSource="tableDataSource" :columns="userTableColumns" v-model:pagination="pagination">
<!--                    数据项-->
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.key==='roleId'">
                            <span v-if="record.roleId==1">管理员</span>
                            <span v-else-if="record.roleId==2">实验员</span>
                            <span v-else-if="record.roleId==3">老师</span>
                            <span v-else-if="record.roleId==4">学生</span>
                            <span v-else>未知身份</span>
                        </template>
<!--                        操作栏-->
                        <template v-if="column.key === 'action'">
                          <span>
                            <a @click="deleteRecord(record)">删除</a>
                              <a-divider type="vertical"/>
                          </span>
                            <span><!--编辑-->
                            <a @click="editRecord(record)">编辑</a>
                              <a-divider type="vertical"/>
                          </span>
                            <span><!--编辑-->
                            <a @click="resetPassword(record)">重置密码</a>
                              <a-divider type="vertical"/>
                          </span>
                        </template>
                    </template>
                </a-table>
        </div>
    </div>
  <!-- 新增表单区域 -->
    <user-add-model @submitSuccess="reloadForm" v-model:formFields="modelFormFields" v-model:openModel="openModel"
                    v-model:modelRoleEditId="modelRoleEditId"
                    v-model:technicianFormState="technicianFormState" v-model:teacherFormState="teacherFormState" v-model:studentFormState="studentFormState"/>
</template>
<script setup lang="ts">


import {ref, reactive, onMounted} from "vue";
import type {TableProps, TableColumnType, FormInstance} from "ant-design-vue";
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import {userTableColumns,modelFormFields, userSearchColumns} from "./user.data.ts";
import UserAddModel from "@/views/user/userAddModel.vue";
import {userDelBatch, $userList, userResetPassword, $userGetById} from "./user.api"
import {message} from "ant-design-vue";
//表单数据
const tableDataSource = reactive([])
// 搜索框收起
const searchExpand = ref(false);
//重置效果
const searchFormRef = ref<FormInstance>();
//保存搜索的信息
const searchFormState = reactive({});

// 分页配置
const pagination=reactive( {
        pageSize: 10, // 每页显示的条数
        showSizeChanger: true, // 是否可以改变每页显示的条数
        pageSizeOptions: ['10', '20', '30', '40'], // 可选的每页显示条数
        showQuickJumper: true, // 是否可以快速跳转到指定页
        showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
        current: 1, // 当前页数
        total:0, // 总条数
        onChange: null // 页码改变时的回调函数,稍后才将器填充进来
})

/**
 * 更新表单函数
 * @param param
 */
const reloadForm=async ()=>{
    const {code,message:returnMessage,data} =  await $userList(searchFormState,{pageNo:pagination.current,pageSize:pagination.pageSize});
    if(data!=null){
        const {records,current,total}= data
        //更新页面数据
        const totalPages = total/pagination.pageSize+1
        if(totalPages<current){
            pagination.current = 1
            await  reloadForm()
            return //阻止执行下面代码
        }
        pagination.total=total
        // 添加新记录到响应式数组
        tableDataSource.length=0
        records.forEach(record => {
            tableDataSource.push(record);
        });
        //输出刷新成功
        message.success("刷新成功")
    }
}

/**
* 搜索的时候调用
 */
const searchDataSource = (values: any) => {
    reloadForm()
};
/**
 * 更换页码信息的时候显示
 * @param page
 * @param pageSize
 */
const handlePageChang=(page, pageSize)=>{//参数为改变后的页码和页码数量
    pagination.current=page
    pagination.pageSize=pageSize
    reloadForm()
}

//*****************************下新增表单**************

const openModel = ref(false);
//新增0,编辑实验员1,编辑老师2,编辑老师3
const modelRoleEditId = ref("0")
let technicianFormState = reactive({});
let teacherFormState = reactive({});
let studentFormState = reactive({});
// 假设technicianFormState, teacherFormState, studentFormState都有相似的属性，比如name, age, roleId
function resetFormStates() {
    Object.keys(technicianFormState).forEach(key => {
        technicianFormState[key] = ''; // 或者其他适当的初始值，如null或默认值
    });
    Object.keys(teacherFormState).forEach(key => {
        teacherFormState[key] = ''; // 同上
    });
    Object.keys(studentFormState).forEach(key => {
        studentFormState[key] = ''; // 同上
    });
}

function showAddModal(){
    //0编辑,1tech.2teach.3student<=roleId:1:root.2tech.3teach.4student
    modelRoleEditId.value = "0"
    resetFormStates()
    openModel.value = true;
}

//****************上新增表单**************************************
/*
数据操作栏目
 */
const cons=(record)=>{
    console.log(record)
    console.log(rowSelection);
}
const editRecord=async (record)=>{
    //record的数据是残缺的,没办法直接使用,需要去后端查询
    //0编辑,1tech.2teach.3student<=roleId:1:root.2tech.3teach.4student
    modelRoleEditId.value=record.roleId - 1
    console.log("等到的record数据",record)
    // const editRecordParam = {userId:record.userId}
    // const resultUser = await $userGetById("",editRecordParam)
    // console.log("resultUser",resultUser)
    switch (modelRoleEditId.value) {
        case "1":
        case 1:
            Object.assign(technicianFormState,record)
            break
        case "2":
        case 2:
            Object.assign(teacherFormState,record)
            break
        case "3":
        case 3:
            Object.assign(studentFormState,record)
            break
    }
    //打开Model
    openModel.value = true
}

const deleteRecord=async (record)=>{
    const id = {id:record.userId}
    try {
        const result = await userDelBatch({},id)
        const {code,message:resultMessage,data} = result
        if(code == "200"){
            message.success(data)
        }else{
            message.error(resultMessage)
        }
    }catch (e){
        message.error("删除用户失败")
    }


    //重新查询界面
    reloadForm();
}
const resetPassword = async (record)=>{
    const id = {userId:record.userId}
    try {
        const result = await userResetPassword({},id)
        const {code,message:resultMessage,data} = result
        if(code == "200"){
            message.success(data)
        }else{
            message.error(resultMessage)
        }
    }catch (e){
        message.error("重置密码失败")
    }
    //重新查询界面
    reloadForm();
}
/**
 * 进来数据加载
 */
onMounted(async () => {
    pagination.onChange=handlePageChang
    await reloadForm();

})

/*
监听选中数据
 */
const rowSelection: TableProps['rowSelection']={
    onChange: (selectedRowKeys: string[], selectedRows: any[]) => {
        selectedRows.forEach(( {key,name,age,address})=>{
            console.log(key,name,age,address)
        })
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
    }),
}


</script>


<style >
* {
    margin: 0;
    padding: 0;
}
.button-div{
    margin:10px
}
.button-div a-button {
    /* 在这里添加你想要的样式 */
    /* 例如： */
    background-color: #007bff; /* 蓝色背景 */
    color: black; /* 白色文本 */
    padding: 10px 20px; /* 内边距 */
    margin:0 100px;
    border: none; /* 去掉边框 */
    border-radius: 5px; /* 圆角 */
    text-decoration: none; /* 去掉下划线 */
    cursor: pointer; /* 鼠标指针形状 */
}

</style>